from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from sqlalchemy import or_
from typing import List, Optional
from datetime import date, datetime
from app.core.database import get_db
from app.core.deps import get_current_admin_user
from app.schemas.project import ProjectCreate, ProjectUpdate, ProjectResponse
from app.models.project import Project, ProjectStatus
from app.models.project_stage import ProjectStage, StageType
from app.models.user import User
from pydantic import BaseModel

router = APIRouter()

def generate_project_number() -> str:
    return f"PRJ{datetime.now().strftime('%Y%m%d%H%M%S')}"

@router.get("", response_model=List[ProjectResponse])
def get_projects(
    skip: int = 0,
    limit: int = 100,
    search: Optional[str] = None,
    apartment_type: Optional[str] = None,
    status: Optional[ProjectStatus] = None,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_admin_user)
):
    query = db.query(Project)
    
    if search:
        query = query.filter(
            or_(
                Project.room_number.contains(search),
                Project.project_number.contains(search)
            )
        )
    if apartment_type:
        query = query.filter(Project.apartment_type == apartment_type)
    if status:
        query = query.filter(Project.status == status)
    
    projects = query.offset(skip).limit(limit).all()
    return projects

@router.post("", response_model=ProjectResponse)
def create_project(
    project: ProjectCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_admin_user)
):
    project_number = project.project_number or generate_project_number()
    
    existing = db.query(Project).filter(
        Project.project_number == project_number
    ).first()
    if existing:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="项目编号已存在"
        )
    
    project_data = project.model_dump(exclude={"project_number"})
    db_project = Project(project_number=project_number, **project_data)
    
    if project.contract_id:
        db_project.status = ProjectStatus.PENDING_START
    
    db.add(db_project)
    db.commit()
    db.refresh(db_project)
    return db_project

@router.get("/{project_id}", response_model=ProjectResponse)
def get_project(
    project_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_admin_user)
):
    project = db.query(Project).filter(Project.id == project_id).first()
    if not project:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="项目不存在"
        )
    return project

@router.put("/{project_id}", response_model=ProjectResponse)
def update_project(
    project_id: int,
    project_update: ProjectUpdate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_admin_user)
):
    project = db.query(Project).filter(Project.id == project_id).first()
    if not project:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="项目不存在"
        )
    
    for key, value in project_update.model_dump(exclude_unset=True).items():
        setattr(project, key, value)
    
    db.commit()
    db.refresh(project)
    return project

class StageRequest(BaseModel):
    stage_date: date
    operator: Optional[str] = None
    content: Optional[str] = None
    status: Optional[str] = None

@router.post("/{project_id}/property")
def add_property_stage(
    project_id: int,
    stage_data: StageRequest,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_admin_user)
):
    project = db.query(Project).filter(Project.id == project_id).first()
    if not project:
        raise HTTPException(status_code=404, detail="项目不存在")
    
    stage = ProjectStage(
        project_id=project_id,
        stage_type=StageType.PROPERTY,
        **stage_data.model_dump()
    )
    db.add(stage)
    project.current_stage = "物业手续"
    db.commit()
    return {"message": "物业手续记录已添加"}

@router.post("/{project_id}/start")
def add_start_stage(
    project_id: int,
    stage_data: StageRequest,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_admin_user)
):
    project = db.query(Project).filter(Project.id == project_id).first()
    if not project:
        raise HTTPException(status_code=404, detail="项目不存在")
    
    stage = ProjectStage(
        project_id=project_id,
        stage_type=StageType.START,
        **stage_data.model_dump()
    )
    db.add(stage)
    project.status = ProjectStatus.IN_PROGRESS
    project.start_date = stage_data.stage_date
    project.current_stage = "施工中"
    db.commit()
    return {"message": "开工记录已添加"}

@router.post("/{project_id}/inspections")
def add_inspection_stage(
    project_id: int,
    stage_data: StageRequest,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_admin_user)
):
    project = db.query(Project).filter(Project.id == project_id).first()
    if not project:
        raise HTTPException(status_code=404, detail="项目不存在")
    
    stage = ProjectStage(
        project_id=project_id,
        stage_type=StageType.INSPECTION,
        **stage_data.model_dump()
    )
    db.add(stage)
    db.commit()
    return {"message": "检查记录已添加"}

@router.post("/{project_id}/acceptance")
def add_acceptance_stage(
    project_id: int,
    stage_data: StageRequest,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_admin_user)
):
    project = db.query(Project).filter(Project.id == project_id).first()
    if not project:
        raise HTTPException(status_code=404, detail="项目不存在")
    
    stage = ProjectStage(
        project_id=project_id,
        stage_type=StageType.ACCEPTANCE,
        **stage_data.model_dump()
    )
    db.add(stage)
    project.status = ProjectStatus.ACCEPTED
    project.completion_date = stage_data.stage_date
    project.current_stage = "已验收"
    db.commit()
    return {"message": "验收记录已添加"}

@router.post("/{project_id}/settlement")
def add_settlement_stage(
    project_id: int,
    stage_data: StageRequest,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_admin_user)
):
    project = db.query(Project).filter(Project.id == project_id).first()
    if not project:
        raise HTTPException(status_code=404, detail="项目不存在")
    
    stage = ProjectStage(
        project_id=project_id,
        stage_type=StageType.SETTLEMENT,
        **stage_data.model_dump()
    )
    db.add(stage)
    project.status = ProjectStatus.SETTLED
    project.current_stage = "已结算"
    db.commit()
    return {"message": "结算记录已添加"}

from app.models.change_order import ChangeOrder, ChangeOrderStatus
from decimal import Decimal

class ChangeOrderRequest(BaseModel):
    change_date: date
    change_content: str
    change_amount: Decimal
    applicant: Optional[str] = None

@router.post("/{project_id}/changes")
def add_change_order(
    project_id: int,
    change_data: ChangeOrderRequest,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_admin_user)
):
    project = db.query(Project).filter(Project.id == project_id).first()
    if not project:
        raise HTTPException(status_code=404, detail="项目不存在")
    
    change_number = f"CHG{datetime.now().strftime('%Y%m%d%H%M%S')}"
    
    change_order = ChangeOrder(
        project_id=project_id,
        change_number=change_number,
        **change_data.model_dump()
    )
    db.add(change_order)
    db.commit()
    return {"message": "变更单已创建", "change_number": change_number}

